#include<iostream>
#include<cstring>
#include<cstdlib>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#define STYLE "[%s@%s %s]# "
#define MAXSIZE 1024
#define ARGVSIZE 128
#define DELIM " "
char* g_argv[ARGVSIZE];
int argc = 0;

const char *GetUser()
{
  return getenv("USER");
}
const char *GetHostName()
{
  return getenv("HOSTNAME");
}
const char *GetCWD()
{
  return getenv("PWD");
}

void commandPormpt()
{

  printf(STYLE, GetUser(),GetHostName(),GetCWD());
  fflush(stdout);
}

bool getCommandLine(char* str)
{
  
    if(fgets(str,MAXSIZE,stdin)== NULL)return false;
    str[strlen(str)-1] = 0;
    if(strlen(str)==0)return false;
    return true;
}

bool cutCommand(char* str)
{
  argc= 0;
  g_argv[argc++] = strtok(str,DELIM);
  while((bool)(g_argv[argc++] = strtok(nullptr,DELIM)));
  argc--;
  return argc>0?true:false;
}

bool checkAndExecCommand()
{
  if(!strcmp(g_argv[0], "cd"))
  {

     return false;
  }
    
  return true;
}

void executeCom()
{
  int status = 0;
  if(fork() == 0)
  {
    execvp(g_argv[0],g_argv);
    printf("Shell: %s: command not found\n",g_argv[0]);
    exit(1);
  }
  waitpid(-1,&status,0);
  return;
}

int main()
{
  while(1)
  {
    //1. 打印命令行提示符
    commandPormpt();
    //2. 获取用户输入
    char str[MAXSIZE];
    if(!getCommandLine(str))continue;  
    //3. 切割字串
    if(!cutCommand(str))continue;
    //4. 判断是否是内置命令
    checkAndExecCommand();
    //5. 执行程序
    executeCom();
  }
  return 0;
}
